package com.sdry.web.controller.workplace;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hacker.base.BaseController;
import com.sdry.model.jyy.Shedudetail;
import com.sdry.model.llm.Classes;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.TeamRecord;
import com.sdry.model.llm.User;
import com.sdry.model.lz.DeviceModel;
import com.sdry.model.workplace.Centrifugal;
import com.sdry.model.workplace.CentrifugalExample;
import com.sdry.model.workplace.CentrifugalExample.Criteria;
import com.sdry.service.hpf.LineSideLibraryService;
import com.sdry.service.jyy.ShedudetailServise;
import com.sdry.service.llm.ClassesService;
import com.sdry.service.llm.TeamRecordService;
import com.sdry.service.workplace.CentrifugalServise;
import com.sdry.service.workplace.OthersService;
import com.sdry.utils.ResponseUtil;


/**
 * @ClassName: centrifugalController
 * @Description: 离心
 * @author tdd
 * @date 2018年8月29日
 * @version V1.0
 */
@Controller
@RequestMapping("/centrifugal")
public class CentrifugalController extends BaseController{
	@Resource
	 private OthersService othersService;
    @Resource
    private CentrifugalServise centrifugalServise;
    @Resource
    private LineSideLibraryService lineSideLibraryServise;
    @Resource
    private TeamRecordService teamRecordService;
    @Resource
    private ShedudetailServise shedudetailServise;
    @Resource
    private ClassesService classesServise;

    /**
     * 添加离心
     * @param response 响应
     * @param centrifugal 离心实体
     * @throws Exception 异常
     */
    @RequestMapping("/insertcentrifugal")
    public void insertcentrifugal(HttpServletRequest request, HttpServletResponse response, Centrifugal centrifugal) throws Exception {

        int affact = 0;

        CentrifugalExample example = new CentrifugalExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(centrifugal.getCtube() != null && centrifugal.getCtube() != "") {
            createCriteria.andCtubeEqualTo(centrifugal.getCtube());
        }
        List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
        if(centrifugals.size() == 0){
            
        	//判断session
      		HttpSession session = request.getSession();
      		// 从session中取出用户身份信息
      		User use = (User) session.getAttribute("currentUser");
      		//当前时间
            SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
            String   date   =   sDateFormat.format(new Date());
            centrifugal.setCoperator(use.getUserName());
            //操作人id
            centrifugal.setCremark2(String.valueOf(use.getUid()));
            centrifugal.setCremark5(use.getRemark3());
            //班组id
            Team team = (Team) session.getAttribute("team");
            centrifugal.setCremark3(String.valueOf(team.getTid()));
            //班次
            centrifugal.setCremark4(team.getCrew());
            centrifugal.setCtime(date);
            //是否报废   1是   0否
            centrifugal.setCremark1("0");
        	//添加
            affact = centrifugalServise.insertSelective(centrifugal);
        }
        ResponseUtil.write(response, affact);
    }
    /**
     * 添加离心
     * @param response 响应
     * @param centrifugal 离心实体
     * @throws Exception 异常
     */
    @RequestMapping("/plInsertcentrifugal")
    public void plInsertcentrifugal(HttpServletRequest req, HttpServletResponse response, Centrifugal centrifugal) throws Exception {
    	String[] listC = req.getParameterValues("listC[]");
    	int affact = 0;
    	//判断session
  		HttpSession session = req.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
  		//当前时间
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        Date dateTime = new Date();
        String date = sDateFormat.format(dateTime);
        centrifugal.setCoperator(use.getUserName());
        //操作人id
        centrifugal.setCremark2(String.valueOf(use.getUid()));
        centrifugal.setCremark5(use.getRemark3());
        //班组id
        Team team = (Team) session.getAttribute("team");
        centrifugal.setCremark3(String.valueOf(team.getTid()));
        //班次
        centrifugal.setCremark4(team.getCrew());
        centrifugal.setCtime(date);
        //是否报废   1是   0否
        centrifugal.setCremark1("0");
    	for (int i = 0; i < listC.length; i++) {
    		centrifugal.setCtube(listC[i]);
    		//添加
    		affact = affact + centrifugalServise.insertSelective(centrifugal);
    		//减库存
    		List<Classes> classesByWrite = classesServise.getClassesByName("白班");
			Classes clas = classesByWrite.get(0);
			//白班的开始时间（小时） 
			Integer startTime = Integer.parseInt(clas.getStartTime().substring(0,2));
			//当天的小时
			Integer hourse = Integer.parseInt(date.substring(11, 13));
			//如果登录时间小于当天的白班的开始时间，则记录上一天
			if(hourse < startTime){
				Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
				ca.setTime(dateTime); //设置时间为当前时间
				ca.add(Calendar.DATE, -1);
				Date last = ca.getTime();
				date = sDateFormat.format(last);
			}
    		TeamRecord teamRecord = teamRecordService.getTeamRecordByTeamAndTime(team.getTid(), date);
    		Shedudetail shedudetail = teamRecordService.selectByPrimaryKey(Integer.parseInt(teamRecord.getProductionId()));
    		String productNumber = "";
    		String atube = listC[i].substring(3, 7);
    		if("0960".equals(atube)){
    			productNumber = "PSH2-0960-T-01";
    		}else if("0980".equals(atube)){
    			productNumber = "PSH2-0980-T-02";
    		}else if("1080".equals(atube)){
    			productNumber = "PSH1-1080-C-04";
    		}else if("1060".equals(atube)){
    			productNumber = "PSH1-1060-B-03";
    		}
    		lineSideLibraryServise.newLineSideLibraryOut(productNumber, "1", shedudetail.getRemark1(), team.getTname(), "1", session, "离心");
    	}
    	if(affact > 0 ){
    		DeviceModel deviceModel = new DeviceModel();
    		//离心机编号
    		deviceModel.setDeviceNo(centrifugal.getCcode());
    		List<DeviceModel> devices = othersService.deviceByMution(deviceModel );
    		int affct = 0;
    		if(devices.size() == 1){
    			deviceModel.setId(devices.get(0).getId());
    			deviceModel.setRemark05("绑定");
    			//修改
    			affct = othersService.deviceUpdate(deviceModel);
    		}
    	}
    	ResponseUtil.write(response, affact);
    }

    /**
     * 带条件的分页查询离心信息
     * @param request 请求
     * @param response 响应
     * @param rows 每页记录数
     * @param page 页数
     * @param centrifugal 离心信息实体
     * @throws Exception 异常
     */
    @RequestMapping("/selectcentrifugalList")
    public void selectcentrifugalList(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "page",required = false)int page,
                                   @RequestParam(value = "rows",required = false)int rows,
                                   Centrifugal centrifugal) throws Exception {

    	PageHelper.startPage(page, rows);

        CentrifugalExample example = new CentrifugalExample();
        example.setOrderByClause("ctime desc");
        Criteria createCriteria =  example.createCriteria();
    	//名称模糊
        if(centrifugal.getCtube() != null && centrifugal.getCtube() != "") {
    		createCriteria.andCtubeLike("%"+centrifugal.getCtube()+"%");
    	}
        createCriteria.andCremarkIsNull();
        //是否报废   1是   0否
        createCriteria.andCremark1EqualTo("0");
		List<Centrifugal> list = centrifugalServise.selectByExample(example);
		
		PageInfo<Centrifugal> info = new PageInfo<Centrifugal>(list);
    	
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("total", info.getTotal());
        jsonObject.put("rows", info.getList());
        ResponseUtil.write(response, jsonObject);
    }

    /**
     * 根据条件查询离心信息
     * @param response 响应
     * @param centrifugal 条件
     * @throws Exception 异常
     */
    @RequestMapping("/selectcentrifugalByExample")
    public void selectcentrifugalByExample(HttpServletResponse response, Centrifugal centrifugal) throws Exception {
        CentrifugalExample example = new CentrifugalExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(centrifugal.getCtube() != null && centrifugal.getCtube() != "") {
            createCriteria.andCtubeEqualTo(centrifugal.getCtube());
        }
        //是否报废   1是   0否
        createCriteria.andCremark1EqualTo("0");
        List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
        //将对象转化为json数组
        JSONArray json = JSONArray.fromObject(centrifugals);
        ResponseUtil.write(response, json);
    }
    /**
     * 根据当前日期产品查询离心信息
     * @param response 响应
     * @param product 产品
     * @throws Exception 异常
     */
    @RequestMapping("/selectNumByDateAndProduct")
    public void selectNumByDateAndProduct(HttpServletRequest request,String product,HttpServletResponse response) throws Exception {
    	CentrifugalExample example = new CentrifugalExample();
    	Criteria createCriteria =  example.createCriteria();
    	//判断session
  		HttpSession session = request.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
		String date = use.getRemark3();
    	//createCriteria.andCtimeLike("%"+date+"%");
		createCriteria.andCremark5Like("%"+date+"%");
    	List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
    	int num  = 0;
    	String size = product.substring(product.length() -2,product.length());
    	String size1 = product.substring(5,9);
    	for (int i = 0; i < centrifugals.size(); i++) {
    		if(size.equals(centrifugals.get(i).getCtube().substring(7,9))){
    			if(size1.equals(centrifugals.get(i).getCtube().substring(3,7))){
    				num++;
    			}
    		}
		}
    	ResponseUtil.write(response, num);
    }
    
    /**
     * 根据当前离心数量
     * @param response 响应
     * @throws Exception 异常
     */
    @RequestMapping("/selectLxNum")
    public void selectLxNum(HttpServletResponse response) throws Exception {
    	CentrifugalExample example = new CentrifugalExample();
    	Criteria createCriteria =  example.createCriteria();
    	//名称查询
    	createCriteria.andCremarkIsNull();
    	//是否报废   1是   0否
        createCriteria.andCremark1EqualTo("0");
    	List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
    	ResponseUtil.write(response, centrifugals.size());
    }
    /**
     * 根据当前年度查询离心信息
     * @param response 响应
     * @throws Exception 异常
     */
    @RequestMapping("/selectNumByYear")
    public void selectNumByYear(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	CentrifugalExample example = new CentrifugalExample();
    	Criteria createCriteria =  example.createCriteria();
    	//判断session
  		HttpSession session = request.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
  		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  		SimpleDateFormat format = new SimpleDateFormat("yyyy");
  		String date = format.format(dateFormat.parse(use.getRemark3()));
    	//createCriteria.andCtimeLike("%"+date+"%");
    	createCriteria.andCremark5Like("%"+date+"%");
    	List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
    	ResponseUtil.write(response, centrifugals.size());
    }
    /**
     * 根据id查询离心信息
     * @param response 响应
     * @param id 离心id
     * @throws Exception 异常
     */
    @RequestMapping("/selectcentrifugalById")
    public void selectcentrifugalById(HttpServletResponse response, Long id) throws Exception {

        Centrifugal centrifugal = centrifugalServise.selectByPrimaryKey(id);
        //将对象转化为json
        JSONObject json = JSONObject.fromObject(centrifugal);
        ResponseUtil.write(response, json);
    }

    /**
     * 修改离心信息
     * @param response 响应
     * @param centrifugal 离心信息
     * @throws Exception 异常
     */
    @RequestMapping("/editcentrifugal")
    public void editcentrifugal( HttpServletResponse response,
                              Centrifugal centrifugal) throws Exception {

        int affct = 0;

        CentrifugalExample example = new CentrifugalExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(centrifugal.getCtube() != null && centrifugal.getCtube() != "") {
            createCriteria.andCtubeEqualTo(centrifugal.getCtube());
        }
        //是否报废   1是   0否
        createCriteria.andCremark1EqualTo("0");
        List<Centrifugal> centrifugals = centrifugalServise.selectByExample(example);
        if(centrifugals.size() == 0){
            //修改
            affct = centrifugalServise.updateByPrimaryKeySelective(centrifugal);
        }else if(centrifugals.size() == 1 && centrifugals.get(0).getCid().equals(centrifugal.getCid())){
            affct = centrifugalServise.updateByPrimaryKeySelective(centrifugal);
        }
        ResponseUtil.write(response, affct);
    }

    /**
     * 批量删除
     * @param response 响应
     * @param ids 离心id
     * @throws Exception 异常
     */
    @RequestMapping("/deletecentrifugal")
    public void deletecentrifugal( HttpServletResponse response, String ids) throws Exception {

        int affact = centrifugalServise.deleteByPrimaryKeys(ids);
        ResponseUtil.write(response, affact);
    }


}
